//
//  VC6Gif.swift
//  ChapterAll
//
//  Created by Kevin on 2020/4/27.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit
import WebKit
import ImageIO

class VC6Gif: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        test2()
    }
    
    func test2() -> Void {
        guard let fileUrl = Bundle.main.url(forResource: "loading", withExtension: ".gif") else {
            return
        }
        // 获取图片数据
        guard let source = CGImageSourceCreateWithURL(fileUrl as CFURL, nil) else {
            return
        }
        // 获取图片数量
        let count = CGImageSourceGetCount(source)
        // 图片播放时长
        var allTime:Float = 0.0
        var imgArr = Array<UIImage>()
        for i in 0..<count {
            if let img = CGImageSourceCreateImageAtIndex(source, i, nil) {
                imgArr.append(UIImage(cgImage: img))
                // 单个图片播放时长
                let info = CGImageSourceCopyPropertiesAtIndex(source, i, nil) as! Dictionary<String, Any>
                let timeDict = info[kCGImagePropertyGIFDictionary as String] as! Dictionary<String,Any>
                let time = timeDict[kCGImagePropertyGIFDelayTime as String]
                // 叠加单个图片时长
                allTime += (time as! NSNumber).floatValue
            }
        }
        let imgView = UIImageView(frame: CGRect(x: 20, y: 200, width: 60, height: 24))
        imgView.animationImages = imgArr
        imgView.animationDuration = TimeInterval(allTime)
        imgView.animationRepeatCount = -1
        view.addSubview(imgView)
        
        imgView.startAnimating()
    }
    
    func test1() -> Void {
        let web = WKWebView(frame: CGRect(x: 100, y: 200, width: 100, height: 100))
        guard let fileUrl = Bundle.main.url(forResource: "loading", withExtension: ".gif") else {
            return
        }
        guard let gifData = try? Data(contentsOf: fileUrl) else {
            return
        }
        web.load(gifData, mimeType: "image/gif", characterEncodingName: "", baseURL: fileUrl)
        view.addSubview(web)
    }
}
